package cn.huiyunche.base.service.utils;

import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 短信http接口的java代码调用示例
 * 基于Apache HttpClient 4.3
 *
 * @author songchao
 * @since 2015-04-03
 */

public class JavaSmsApi {

    private static final Logger LOGGER = LoggerFactory.getLogger(JavaSmsApi.class);
    //查账户信息的http地址
    private static String URI_GET_USER_INFO = "https://sms.yunpian.com/v2/user/get.json";

    //智能匹配模板发送接口的http地址
    private static String URI_SEND_SMS = "https://sms.yunpian.com/v2/sms/single_send.json";

    //模板发送接口的http地址
    private static String URI_TPL_SEND_SMS = "https://sms.yunpian.com/v2/sms/tpl_single_send.json";

    //发送语音验证码接口的http地址
    private static String URI_SEND_VOICE = "https://voice.yunpian.com/v2/voice/send.json";

    //编码格式。发送编码格式统一用UTF-8
    private static String ENCODING = "UTF-8";

    //apikey
    private static String API_KEY = "2ac15041e43d472237ff9ea879267a08";

    //设置模板ID，如使用1号模板:【#company#】您的验证码是#code#
    public static final long TPL_ID = 1478069;

    //提现模板ID
    public static final long CASH_TPL_ID = 1502842;
    /*
     * 1.提车安排通知
		发送时机：录入提车安排
		发送对象：此运单的下单商户
		发送内容：［慧运车］您由北京托至乌鲁木齐的订单CO786747290820919296，已安排提车人张三身份证号120111198002022222电话13888888888，提车4辆。
     */
    public static final long EXTRACTED_TPL_ID = 1605876;
    public static final long VENEER_EXTRACTED_TPL_ID = 1636100;
    public static final long VENEER_JIAOCHEREN_TPL_ID = 1636106;
    /*
     * 2.确认交车安排通知
		发送时机：每个运单被交车审核完毕后均发送
		发送对象：此运单的下单商户
		发送内容：［慧运车］您由北京托至乌鲁木齐的订单CO786747290820919296托运4辆汽车已经达目的地，请您确认交车。
     */
    public static final long DELIVERY_TPL_ID = 1605882;
    public static final long VENEER_DELIVERY_TPL_ID = 1636112;
    // 系统给司机派单jiek
    public static final long DISPATCHDRIVER_TPL_ID = 1619986;
    // 系统给司机回单jiek
    public static final long RESULTDRIVER_TPL_ID = 1628506;
    // 系统给司机发送发运信息
    public static final long DEPARTURE_TPL_ID = 1809008;
    // 系统给司机派单失败jiek
    public static final long DISPATCHDRIVERERROR_TPL_ID = 1628656;
    // 系统给司机意向路线不匹配jiek
    public static final long INTENTIONALLINESDRIVERERROR_TPL_ID = 1675068;
    // 系统异常通知
    public static final long DISPATCHSTSTEM_TPL_ID = 1634964;
    // 商户生成账单发送短信
    public static final long KELECOMPANY_BILL_TPL_ID = 1639700;
    // 易宝回调成功通知
    public static final long YEEPAY_NOTIFY_SUCCESS_TPL_ID = 1683282;
    // 易宝回调失败通知
    public static final long YEEPAY_NOTIFY_ERROR_TPL_ID = 1683278;

    // 派单时司机用户不可用
    public static final long USER_IS_DISABLE = 1725890;

    //派单司机有未完成的运单
    public static final long USER_ALREADY_EXISTS_WAYBILL = 1725894;

    /**
     * DRIVER_INFO_ERROR(0, "获取司机关联信息失败"),
     * DRIVER_HAS_NO_IDCARD(101, "需要提供身份证号"),
     * DRIVER_HAS_NO_PHONE_NO(102, "需要提供手机号"),
     * DRIVER_UPDATE_INFO_ERROR(103, "读取/更新司机信息错误"),
     * DRIVER_IS_NOT_TMS_DRIVER(104, "非知车司机，不可以安排"),
     * DRIVER_HAS_NO_LICENSE(106, "司机确实缺少驾照类型"),
     * DRIVER_LICENSE_NOT_MATCH(107, "司机驾照不匹配驾照类型"),
     * DRIVER_HAS_NO_INTENTIONA_LINE(108, "司机驾照不匹配驾照类型"),
     * DRIVER_IS_DISABLE(109, "司机不可用"),
     * DRIVER_ALREADY_HAVE_WAYVILL(110, "司机已经有未完成的运单"),
     * DRIVER_INFO_SYSTEM_ERROR(110, "系统司机信息错误"),
     */
    public static final long DRIVER_INFO_ERROR = 1726154;
    public static final long DRIVER_HAS_NO_IDCARD = 1726156;
    public static final long DRIVER_HAS_NO_PHONE_NO = 1726158;
    public static final long DRIVER_UPDATE_INFO_ERROR = 1726154;
    public static final long DRIVER_IS_NOT_TMS_DRIVER = 1628656;
    public static final long DRIVER_HAS_NO_LICENSE = 1726162;
    //    public static final long DRIVER_LICENSE_NOT_MATCH = 1726162;
    public static final long DRIVER_HAS_NO_INTENTIONA_LINE = 1675068;
    public static final long DRIVER_IS_DISABLE = 1725890;
    public static final long DRIVER_ALREADY_HAVE_WAYVILL = 1725894;
    public static final long DRIVER_INFO_SYSTEM_ERROR = 1725894;

    // 订单交车照片审核通过
    public static final long WAYBILL_AUDIT_PASS = 1762454;
    // 订单交车照片审核通过-异常
    public static final long WAYBILL_AUDIT_PASS_APPROVE = 1762456;
    // 订单交车照片审核通过-不可排队
    public static final long WAYBILL_AUDIT_PASS_FORBIDDEN = 1762458;


    public static void main(String[] args) throws IOException, URISyntaxException {

        //修改为您的apikey.apikey可在官网（http://www.yuanpian.com)登录后获取
        String apikey = "2ac15041e43d472237ff9ea879267a08";

        //修改为您要发送的手机号
        String mobile = "18612675471";

        /**************** 查账户信息调用示例 *****************/
        System.out.println(JavaSmsApi.getUserInfo(apikey));

        /**************** 使用智能匹配模板接口发短信(推荐) *****************/
        //设置您要发送的内容(内容必须和某个模板匹配。以下例子匹配的是系统提供的1号模板）
//        String text = "【云片网】您的验证码是1234";
        //发短信调用示例
        // System.out.println(JavaSmsApi.sendSms(apikey, text, mobile));

        /**************** 使用指定模板接口发短信(不推荐，建议使用智能匹配模板接口) *****************/
        //设置模板ID，如使用1号模板:【#company#】您的验证码是#code#
        long tpl_id = 1478069;
        //设置对应的模板变量值

        String tpl_value = URLEncoder.encode("#code#", getENCODING()) + "="
                + URLEncoder.encode("1234", getENCODING()) + "&"
                + URLEncoder.encode("#company#", getENCODING()) + "="
                + URLEncoder.encode("云片网", getENCODING());
        //模板发送的调用示例
        System.out.println(tpl_value);
        System.out.println(JavaSmsApi.tplSendSms(apikey, tpl_id, tpl_value, mobile));

        /**************** 使用接口发语音验证码 *****************/
//        String code = "1234";
        //System.out.println(JavaSmsApi.sendVoice(apikey, mobile ,code));
    }

    /**
     * 取账户信息
     *
     * @return json格式字符串
     * @throws java.io.IOException
     */

    public static String getUserInfo(String apikey) throws IOException, URISyntaxException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        return post(URI_GET_USER_INFO, params);
    }

    /**
     * 智能匹配模板接口发短信
     *
     * @param apikey apikey
     * @param text   　短信内容
     * @param mobile 　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */

    public static String sendSms(String apikey, String text, String mobile) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("text", text);
        params.put("mobile", mobile);
        return post(URI_SEND_SMS, params);
    }

    /**
     * 通过模板发送短信(不推荐)
     *
     * @param apikey    apikey
     * @param tpl_id    　模板id
     * @param tpl_value 　模板变量值
     * @param mobile    　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */
    public static String tplSendSms(String apikey, long tpl_id, String tpl_value, String mobile) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("tpl_id", String.valueOf(tpl_id));
        params.put("tpl_value", tpl_value);
        params.put("mobile", mobile);
        return post(URI_TPL_SEND_SMS, params);
    }

    /**
     * 通过接口发送语音验证码
     *
     * @param apikey apikey
     * @param mobile 接收的手机号
     * @param code   验证码
     * @return
     */

    public static String sendVoice(String apikey, String mobile, String code) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("mobile", mobile);
        params.put("code", code);
        return post(URI_SEND_VOICE, params);
    }

    /**
     * 基于HttpClient 4.3的通用POST方法
     *
     * @param url       提交的URL
     * @param paramsMap 提交<参数，值>Map
     * @return 提交响应
     */

    public static String post(String url, Map<String, String> paramsMap) {
        CloseableHttpClient client = HttpClients.createDefault();
        String responseText = "";
        CloseableHttpResponse response = null;
        try {
            HttpPost method = new HttpPost(url);
            RequestConfig.Builder builder = RequestConfig.custom().setConnectTimeout(300000).setSocketTimeout(60000);
            method.setConfig(builder.build());
            if (paramsMap != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> param : paramsMap.entrySet()) {
                    NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
                    paramList.add(pair);
                }
                method.setEntity(new UrlEncodedFormEntity(paramList, getENCODING()));
            }
            response = client.execute(method);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseText = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            throw new BusinessException("HttpPost请求异常!");
            //LOGGER.error("HttpPost请求异常");
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(responseText);
        return responseText;
    }

    public static String getAPIKEY() {
        return API_KEY;
    }

    public static void setAPIKEY(String aPI_KEY) {
        API_KEY = aPI_KEY;
    }

    public static String getENCODING() {
        return ENCODING;
    }

    public static void setENCODING(String eNCODING) {
        ENCODING = eNCODING;
    }
}
